#!/usr/bin/perl -T

=head1 NAME

Send-reminders - send email reminders for special occasions

=head1 SYNOPSIS

Send emails reminders set by users for special occasions.

=head1 DESCRIPTION

Email-reminder allows users to define events that they want to be
reminded of by email.  Possible events include birthdays,
anniversaries and yearly events.  Reminders can be sent on the day of
the event and a few days beforehand.

This script is meant to be invoked everyday by a cron job.  It mails
the actual reminders out.

When run by the root user, it processes all of the spooled reminders.
When run by a specific user, it only processes reminders set by that
user.

=head1 OPTIONS

=over 6

=item B<--help>

Displays basic usage message.

=item B<--simulate>

Does not actually send any emails out.

=item B<--verbose>

Prints out information about what the program is doing, including the
full emails being sent out.

=item B<--version>

Displays the version number.

=back

=head1 FILES

F<~/.email-reminders>, F</etc/email-reminder.conf>

=head1 AUTHOR

Francois Marier <francois@debian.org>

=head1 SEE ALSO

email-reminder-editor, collect-reminders

=head1 COPYRIGHT

Copyright (C) 2004-2008 by Francois Marier

Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.

Email-Reminder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.

=cut

use strict;
use warnings;

use Encode;
use Getopt::Long;
use MIME::Base64;
use MIME::QuotedPrint;
use Net::SMTP;
use Pod::Usage;

use EmailReminder::EventList;
use EmailReminder::Utils;
use Date::Manip qw(ParseDate UnixDate);

# Default preferences
my $PREFERENCE_FILE = '/etc/email-reminder.conf';
my %preferences;
$preferences{"send_reminders"}   = 1;
$preferences{"smtp_server"}      = 'localhost';
$preferences{"smtp_username"}    = '';
$preferences{"smtp_password"}    = '';
$preferences{"mail_from"}        = 'root@localhost';
read_config(); 

# Global variables
my $user_fname;
my $user_lname;

# Command-line parameters
my $verbose  = 0;
my $simulate = 0;
my $version  = 0;
my $help  = 0;
GetOptions( "verbose"  => \$verbose,
            "simulate" => \$simulate,
            "version"  => \$version,
            "help"     => \$help,
    );

# Override preferences with system values
sub read_config
{
    if (open CONFIG, '<', $PREFERENCE_FILE)
    {
        print "Reading preferences from '$PREFERENCE_FILE'\n" if $verbose;

        # Stolen off of the Cookbook (section 8.16)
        while (<CONFIG>) {
            chomp;                  # no newline
            s/#.*//;                # no comments
            s/^\s+//;               # no leading white
            s/\s+$//;               # no trailing white
            next unless length;     # anything left?
            my ($var, $value) = split(/\s*=\s*/, $_, 2);
            $preferences{$var} = $value;
        }
        
        close CONFIG;
    }
    else {
        print "Warning: cannot read configuration file at $PREFERENCE_FILE.\nMake sure that the user running $0 has read permissions on that configuration file.\n";
    }
}

sub send_email
{
    my $message = shift;
    my $subject = shift;
    my $user_name = shift;
    my $user_email = shift;

    unless ($user_email) {
        return 0;
    }

    my $to = $user_email;
    $to = "$user_name <$user_email>" if ($user_name);

    print "--> Emailing '$to':\n".encode("UTF-8", $subject."\n\n".$message) if $verbose;
    
    unless ($simulate) {
        my $smtp_server = '';
        if ($preferences{"smtp_server"} =~ /^([A-Za-z_0-9\-\/.]+)$/) {
            $smtp_server = $1;
        }
        my $smtp = Net::SMTP->new($smtp_server, Debug => 0);
        die "Error: couldn't connect to server '$smtp_server'" unless $smtp;

        # SMTP SASL authentication (if necessary)
        if ($preferences{"smtp_username"} and $preferences{"smtp_password"}) {
            unless ($smtp->auth($preferences{"smtp_username"}, $preferences{"smtp_password"})) {
                die "Error: authentication with the SMTP server failed with error code ".$smtp->status;
            }
        }

        unless ($smtp->mail($preferences{"mail_from"})) {
            die "Error: the sending address was not accepted. Try setting the 'mail_from' variable to a valid email address in the configuration file";
        }

        my $ok = 1;
        $ok = $ok && $smtp->to($to);
        $ok = $ok && $smtp->data();
        $ok = $ok && $smtp->datasend("From: Email-Reminder <" . $preferences{"mail_from"} . ">\n");
        
        # Create an RFC822 compliant date (current time)
        my $rfc822_format = "%a, %d %b %Y %H:%M %z";
        my $today         = ParseDate("Now");
        my $rfc822_date = UnixDate($today,$rfc822_format);
        $ok = $ok && $smtp->datasend("Date: $rfc822_date\n");
        
        $ok = $ok && $smtp->datasend("To: $to\n");
        $ok = $ok && $smtp->datasend("Subject: =?utf-8?B?".encode_base64(encode("UTF-8", $subject), '')."?=\n");
        $ok = $ok && $smtp->datasend("Mime-Version: 1.0\n");
        $ok = $ok && $smtp->datasend("Content-Type: text/plain; charset=utf-8\n");
        $ok = $ok && $smtp->datasend("Content-Disposition: inline\n");
        $ok = $ok && $smtp->datasend("Content-Transfer-Encoding: quoted-printable\n");
        $ok = $ok && $smtp->datasend("\n");
        $ok = $ok && $smtp->datasend(encode_qp(encode("UTF-8", $message)));
        $ok = $ok && $smtp->dataend();

        $smtp->quit();

        die "Error: could not mail the reminder out" unless $ok;
    }

    return 1;
}

sub process_file
{
    my $file = shift;

    print "==> Processing $file\n" if $verbose;

    my $list = EmailReminder::EventList->new($file);

    my @fullname = $list->get_user_name();
    my $user_fname = $fullname[0];
    my $user_lname = $fullname[1];
    my $user_name = $user_fname;
    $user_name .= " " . $user_lname if defined($user_lname);
    my $user_email = $list->get_user_email();

    foreach my $event ($list->get_events()) {
        if ($event->is_occurring()) {
            my $msg = $event->get_message($user_fname);
            my $subject = $event->get_subject();

            my @recipients = @{$event->get_recipients()};
            if ($#recipients > -1) {
                foreach my $recipient (@recipients) {
                    my $recipient_email = shift @{$recipient};
                    my $recipient_name = shift @{$recipient};
                    my $success = send_email($msg, $subject, $recipient_name, $recipient_email) if $msg;
                    return 0 if !$success;
                }
            } else {
                my $success = send_email($msg, $subject, $user_name, $user_email) if $msg;
                return 0 if !$success;
            }
        }
    }

    return 1;
}

sub main
{
    my $running_uid = $>;
    if (0 == $running_uid) {
        print STDERR "Warning: for security reasons, this script should not be not as root.\n";
    }

    my $spool_dir = $EmailReminder::Utils::SPOOL_DIRECTORY;
    if (-w $spool_dir) {
        # Iterate through all spooled files
        while (defined(my $file = <$spool_dir/*>)) {
            # Untaint filename
            if ($file =~ /^([A-Za-z_0-9\-\/]+)$/) {
                $file = $1;
            } else {
                print STDERR "Skipped unclean filename" if $verbose;
                next;
            }

            unless (process_file($file, 0, 1)) {
                return 0;
            }

            # Delete the file once we're done with it
            unless (unlink($file)) {
                print STDERR "Could not remove $file.\n" if $verbose;
            }
        }
        return 1;
    } else {
        # Normal users only get to test their own reminders
        my @pwinfo = getpwuid($>);
        my $homedir = $pwinfo[7];
        my $file = "$homedir/" . $EmailReminder::Utils::USER_CONFIG_FILE;

        if (-e $file) {
            return process_file($file, 0, 1);
        } else {
            print STDERR "Warning: could not find your .email-reminders file.\n";
            return 0;
        }
    }
}

if ($help || $version) {
    print "send-reminders $EmailReminder::Utils::VERSION\n";
    if ($help) {
        print "\n";
        pod2usage(1);
    }
} elsif ($preferences{"send_reminders"}) {
    unless (main()) {
        print STDERR "Could not send reminders.\n";
    }
}
